package com.example.demo.rabbitmq;

import com.example.demo.util.ByteUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.impl.AMQImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: Scott
 * @Description:
 * @Date: Create in 11:58 2018/1/26
 * 发布消息需要制定路由
 *默认的路由 发送的时候发送的队列的名字就是路由的名字，如果使用默认的路由，路由的名字可以写成队列的名字，因为直接发送的来同样的队列的名字里了
 */
@Slf4j
@Service
public class MQSendUtil {
    @Autowired
    private ConnectionFactory factory;

    public void send(Object target, String queneName,String routKey,String exchane) {

        try {
            Connection connection = factory.newConnection();

            Channel channel = connection.createChannel();
            channel.exchangeDeclare(exchane, "topic");
            //发送的
            channel.basicPublish(exchane, routKey, null, ByteUtil.getBytes(target));

            System.out.println("已发送"+target);
            channel.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("发送失败{}", target);
        }
    }

}
